<?php


namespace api\user\controller;


use api\user\model\LoginModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class PayController extends RestBaseController
{
    public function PayCreate(Request $request)
    {
        $order_id = input('post.order_id');
        $order = Db::name('order')
            ->where('trade_no','=',$order_id)
            ->find();
        if(!$order)
        {
            $this->error('订单不存在');
        }
        if($order['status'] != 0)
        {
            $this->error('该订单已支付');
        }
        //查询
        $money = Db::name('money')
            ->where('user_id','=',$request->user_id)
            ->find();
        //查询用户
        $user = LoginModel::where('id','=',$request->user_id)
            ->find();
        //判断余额是否足够
        if($user['wallet'] < $order['total_price']){
            $this->error('余额不足');
        }
        Db::startTrans();
        $updateOrderStatus = false;
        $updateUserWallet = false;
        $moneyLog = false;
        try {
            //订单状态改为1
            $updateOrderStatus = Db::name('order')
                ->where('trade_no','=',$order_id)
                ->update(['status'=>1,
                    'pay_type'=>'账户余额支付']);
            //用户余额改变
            $user->wallet = $user['wallet'] - $order['total_price'];
            $updateUserWallet = $user->save();
            //创建消费记录
            $moneyLog = Db::name('money')
                ->insert([
                    'user_id'=>$request->user_id,
                    'wallet'=>$order['total_price'],
                    'before'=>$user['wallet'],
                    'after'=>$user['wallet'] - $order['total_price'],
                    'type'=>'0',
                    'create_time'=>date('Y:m:d H:i:s')
                ]);

        }catch (\Exception $e){
            Db::rollback();
        }
        if ($updateOrderStatus && $updateUserWallet && $moneyLog) {
            // 提交事务
            Db::commit();
            $this->success('支付成功');
        } else {
            // 回滚事务
            Db::rollback();
            $this->error('支付失败');
        }
    }
}
